package com.qf.smartplatform.controller.advice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.smartplatform.constans.ResultCode;
import com.qf.smartplatform.dto.R;
import com.qf.smartplatform.exceptions.MyBaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

@RestControllerAdvice
public class MyControllerAdvice {
    private ObjectMapper objectMapper;
    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    /**
     * 自定义异常处理器
     * @param exception
     * @return
     */
    @ExceptionHandler
    public R processBaseException(MyBaseException exception){
        exception.printStackTrace();
        return R.getResult(exception.getCode(),exception.getMessage());
    }
    @ExceptionHandler
    public R processMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
//        exception.getBindingResult().getAllErrors().forEach(objectError -> {
//            String defaultMessage = objectError.getDefaultMessage();
//            System.out.println(defaultMessage);
//        });
        exception.printStackTrace();
        String defaultMessage = exception.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        System.out.println(defaultMessage);
        try {
            Map map = objectMapper.readValue(defaultMessage, Map.class);
            int code = (int)map .get("code");
            String msg = (String) map.get("msg");
            return R.getResult(code,msg);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return R.ERROR();
    }

    @ExceptionHandler(Exception.class)
    public R processBaseException(Exception exception) {
        exception.printStackTrace();
        return R.getResult(ResultCode.FAIL, "网络异常,请检查您的网络");
    }

}
